package com.wn.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat.getColor
import androidx.core.view.isVisible
import com.wn.common.databinding.ViewEmptyDataBinding

/**
 * @Author: wn
 * @Date: 2024/10/29 15:08
 * @Description: 空数据 占位 自定义 view
 */
class EmptyDataView @JvmOverloads constructor(
  context: Context,
  attrs: AttributeSet? = null,
  defStyleAttr: Int = 0,
) : LinearLayout(context, attrs, defStyleAttr) {

  private var mBinding: ViewEmptyDataBinding

  init {
    mBinding = ViewEmptyDataBinding.inflate(LayoutInflater.from(context), this, true)
    orientation = VERTICAL
    gravity = Gravity.CENTER
    layoutParams = ViewGroup.LayoutParams(
      ViewGroup.LayoutParams.MATCH_PARENT,
      ViewGroup.LayoutParams.MATCH_PARENT
    )
    obtainAttributes(context, attrs)
  }

  // xml 中 自定义属性
  private fun obtainAttributes(context: Context, attrs: AttributeSet?) {
    attrs?.let {
      val ta = context.obtainStyledAttributes(attrs, com.wn.framework.R.styleable.EmptyDataView)
      val emptyText = ta.getString(com.wn.framework.R.styleable.EmptyDataView_emptyText)
      val emptyImage =
        ta.getResourceId(
          com.wn.framework.R.styleable.EmptyDataView_emptyImage,
          com.wn.framework.R.mipmap.ic_data_empty
        )
      val bgColor = ta.getColor(
        com.wn.framework.R.styleable.EmptyDataView_bg_color,
        getColor(context, com.wn.framework.R.color.white)
      )
      val emptyPaddingBottom = ta.getDimension(
        com.wn.framework.R.styleable.EmptyDataView_emptyPaddingBottom, 0.0f
      ).toInt()
      ta.recycle()

      if (!emptyText.isNullOrEmpty()) {
        mBinding.tvNoData.text = emptyText // 没有默认值
      }
      mBinding.ivNoData.setImageResource(emptyImage)
      setBackgroundColor(bgColor)
      setPadding(0, 0, 0, emptyPaddingBottom)
    }
  }

  /**
   * 代码 中 自定义属性 -- 背景颜色
   * @param colorId Int
   * @return EmptyDataView
   */
  fun setBgColor(colorId: Int): EmptyDataView {
    setBackgroundColor(colorId)
    return this
  }

  /**
   * 代码 中 自定义属性 -- 图片展示内容
   * @param resId Int
   * @return EmptyDataView
   */
  fun setImageResource(resId: Int): EmptyDataView {
    if (resId == 0) {
      mBinding.ivNoData.isVisible = false
      return this
    }
    mBinding.ivNoData.isVisible = true
    mBinding.ivNoData.setImageResource(resId)
    return this
  }

  /**
   * 代码 中 自定义属性 -- 文字展示内容
   * @param str String?
   * @return EmptyDataView
   */
  fun setText(str: String?): EmptyDataView {
    mBinding.tvNoData.text = str
    return this
  }
}